import axios from 'axios'
import { ElMessage } from 'element-plus'

// ===== 常量定义 =====
const API_BASE_URL = 'http://xvr8a0okpffe-7095.beijing-01.dayunet.com:80'
const DEFAULT_TIMEOUT = 30000
const DEFAULT_PAGE_SIZE = 10

// ===== Axios 实例配置 =====
const api = axios.create({
  baseURL: API_BASE_URL,
  headers: {
    'Content-Type': 'application/json',
    Accept: 'application/json'
  },
  timeout: DEFAULT_TIMEOUT,
  withCredentials: false
})

// ===== 拦截器 =====
// 请求拦截器
api.interceptors.request.use(
  (config) => {
    console.log('Sending request:', config)

    // 获取管理员角色和对应token
    const isAdmin = localStorage.getItem('admin-role') === 'admin'
    const tokenValue = isAdmin
      ? localStorage.getItem('admin-token')
      : localStorage.getItem('user-token')

    // 设置请求头
    config.headers = {
      ...config.headers,
      token: tokenValue
      // 'Content-Type': 'application/json',
      // Accept: 'application/json'
    }

    return config
  },
  (error) => {
    console.error('Request error:', error)
    return Promise.reject(error)
  }
)

// 响应拦截器
api.interceptors.response.use(
  (response) => {
    if (response.data?.data) {
      console.log('Response data:', response.data)
    }
    return response
  },
  (error) => {
    console.error('Response error:', error)

    // 处理错误响应
    if (error.response) {
      handleHttpError(error.response)
    } else if (error.request) {
      ElMessage.error('无法连接到服务器，请检查网络')
    } else {
      ElMessage.error('请求配置错误')
    }

    return Promise.reject(error)
  }
)

// ===== 错误处理 =====
const handleHttpError = (response) => {
  const errorMessages = {
    401: '未授权，请重新登录',
    403: '没有权限访问该资源',
    502: '服务器网关错误，请稍后重试',
    503: '服务暂时不可用，请稍后重试',
    504: '服务器网关超时',
    600: '用户名不存在'
  }

  const status = response.status
  const message = response.data?.message || errorMessages[status] || '请求失败'

  if (status === 401) {
    // 清除所有认证信息
    clearAuthInfo()
    // 跳转到登录页
    redirectToLogin()
  }

  ElMessage.error(message)
}

// ===== 工具函数 =====
// 清除认证信息
const clearAuthInfo = () => {
  const items = ['user-token', 'admin-token', 'admin-role']
  items.forEach((item) => {
    localStorage.removeItem(item)
    sessionStorage.removeItem(item)
  })
}

// 重定向到登录页
const redirectToLogin = () => {
  if (window.vueRouter) {
    window.vueRouter.push('/login')
  } else {
    window.location.href = '/login'
  }
}

// ===== API 接口定义 =====
// 用户相关接口
export const userApi = {
  // 认证相关
  login: (loginInfo) => {
    return api({
      method: 'post',
      url: '/login',
      data: {
        username: loginInfo.username,
        passward: loginInfo.passward,
        role: loginInfo.role
      }
    })
  },

  register: (registerInfo) => {
    return api.post('/register', {
      username: registerInfo.username,
      passward: registerInfo.passward
    })
  },

  // 用户管理
  getUsers: (params = {}) => {
    return api.post('/listuser', null, {
      params: {
        username: params.username || '',
        role: params.role || '',
        page: params.page || 1,
        pageSize: params.pageSize || DEFAULT_PAGE_SIZE
      }
    })
  },

  getRoles: () => {
    return api.post('/role', null, { params: {} })
  },

  createUser: (userData) => {
    return api.post('/adduser', {
      username: userData.username,
      passward: userData.passward,
      roleId: userData.roleId
    })
  },

  deleteUser: (userData) => {
    return api.post('/deleteuser', null, {
      params: { id: userData.id }
    })
  },

  updateUserStatus: (userData) => {
    const url = userData.status === 1 ? '/enable' : '/disable'
    return api({
      method: 'post',
      url,
      headers: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      params: {
        username: userData.username,
        role: userData.role
      }
    })
  },

  updateUserRole: (userData) => {
    const role = userData.roleId === '2' ? 'admin' : 'user'

    return api.put('/updateRole', null, {
      params: {
        id: userData.id,
        role: role
      }
    })
  }
}

// 团队相关接口
export const teamApi = {
  // 团队基本操作
  getTeams: () => api.post('/team'),
  getTeamInfo: () => api.post('/teamteam'),
  createTeam: (teamname) => api.post('/newteam', { teamname }),

  // 团队实验管理
  getTeamExperiments: (params = {}) => {
    return api.post('/teamexp', {
      current: params.current || 1,
      pageSize: params.pageSize || DEFAULT_PAGE_SIZE,
      experimentName: params.experimentName || '',
      teamname: params.teamname || ''
    })
  },

  // 团队成员管理
  getTeamMembers: (teamname) => api.post('/teamteam', { teamname }),

  deleteTeamMember: (data) => {
    return api.post('/deleteteam', {
      username: data.username,
      teamname: data.teamname
    })
  },

  modifyTeamMemberRole: (data) => {
    return api.post('/modifyteam', {
      username: data.username,
      teamname: data.teamname,
      role: data.role
    })
  },

  // 团队角色管理
  getRoles: () => api.post('/teamrole'),

  // 团队邀请管理
  generateInviteLink: (teamname) => api.post('/generatelink', { teamname }),

  joinTeamByLink: (data) => api.post('/join1', { link: data.link }),

  joinTeamByLeader: (data) => {
    return api.post('/join2', {
      username: data.username,
      teamName: data.teamname
    })
  }
}

export default api
